/*
 * @Author: chen17
 * @Date: 2022-03-30 11:45:06
 * @LastEditTime: 2023-10-09 15:37:43
 * @Description: 权限菜单管理
 */

import router, { resetRouter } from '@/router'
import { getPermissionRouters } from '@/api/login'
import { constantRoutes, dashboardRoute } from '@/router'
import { dealRoutes, filterPermissionRoutes, deepClone } from '@/utils/index'

const state = {
    // 展示的权限路由
    authRoutes: []
}

const mutations = {
    set_auth_routes: (state, routes) => {
        state.authRoutes = routes
    }
}

const actions = {
    // 初始化权限路由
    initAuthRoutes({ commit }) {
        return new Promise((resolve, reject) => {
            getPermissionRouters()
                .then(res => {
                    // 接口获取权限路由
                    let apiRoutes = res.data || []
                    // 深拷贝数据 - 数据源被修改问题
                    let cloneConstantRoutes = deepClone(constantRoutes)
                    // 通过配置的权限路由修改本地路由
                    let dealRouteList = dealRoutes(cloneConstantRoutes, apiRoutes)
                    // 过滤有权限的路由列表
                    let hasPermissionRoutes = filterPermissionRoutes(dealRouteList)
                    // 添加权限路由和错误页面到router
                    router.addRoutes([
                        ...hasPermissionRoutes,
                        {
                            path: '*',
                            redirect: '/404',
                            hidden: true
                        }
                    ])
                    // 合并首页路由和权限路由
                    const routes = [dashboardRoute, ...hasPermissionRoutes]
                    commit('set_auth_routes', routes)
                    resolve(true)
                })
                .catch(error => {
                    reject(error)
                })
        })
    },
    // 重置权限路由
    resetAuthRoutes({ commit }) {
        resetRouter()
        commit('set_auth_routes', [])
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
